package com.atguigu.flink.streamapi.trans;

import com.atguigu.flink.function.WaterSensorMapFunction;
import com.atguigu.flink.pojo.WaterSensor;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

/**
 * Created by Smexy on 2023/1/13
 */
public class Demo7_Reduce
{
    public static void main(String[] args) {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

                env
                   .socketTextStream("hadoop103", 8888)
                   .map(new WaterSensorMapFunction())
                   .keyBy(WaterSensor::getId)
                   .reduce(new ReduceFunction<WaterSensor>()
                   {
                       /*
                            两两聚合，之后的返回值，会赋值给value1。
                            每次输入的数据，作为value2.
                            如果当前是第一条数据，这条数据，作为value1返回！
                        */
                       @Override
                       public WaterSensor reduce(WaterSensor value1, WaterSensor value2) throws Exception {
                           System.out.println("Demo7_Reduce.reduce");

                           int maxVc = Math.max(value1.getVc(), value2.getVc());
                           //实现max(vc)的效果  取最大值，其他字段以当前组的第一个为主
                           //value1.setVc(maxVc);
                           //实现maxBy(vc)的效果  取当前最大值的所有字段
                           if (value1.getVc() > value2.getVc()){
                               value1.setVc(maxVc);
                               return value1;
                           }else {
                               value2.setVc(maxVc);
                               return value2;
                           }
                       }
                   })
                   .print();

                try {
                            env.execute();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

    }
}
